<?php

namespace App\Services;

use Illuminate\Support\Facades\Storage;

class CollectionCodeService
{
    public function createCollectionCode($data)
    {
        // 完全按老项目实现
        $width = 320;
        $height = 440;
        $logo_width = 40;
        $logo_height = 40;
        $font_size_show = 20;

        $member_id = auth()->id() ?? 0;

        // 商城信息（此处仅用到顶部背景图与店名）
        $shopInfoName = '商城';
        $shopImg = public_path('static/images/photo-mr.jpg');

        $shopName = $data['custom_text'] ?? '商城';
        $str_lenght = $logo_width + $font_size_show * mb_strlen($shopName);
        $space = ($width - $str_lenght) / 2;

        $uniacid = 1;
        $path = storage_path('app/public/collection-code/' . $uniacid);
        if (!file_exists($path)) {
            mkdir($path, 0755, true);
        }

        $md5 = md5($member_id . $shopInfoName . $shopImg . '2' . $data['type'] . $data['store_id']);
        $extend = '.png';
        $file = $md5 . $extend;

        $targetImg = imagecreatetruecolor($width, $height);
        // 主题色（与老项目接近）
        $orange = imagecolorallocate($targetImg, 241, 91, 13);
        $whiteReal = imagecolorallocate($targetImg, 255, 250, 250);
        $whitePure = imagecolorallocate($targetImg, 255, 255, 255);

        // 整体背景白色
        imagefilledrectangle($targetImg, 0, 0, $width, $height, $whitePure);
        // 顶部白色留白条
        imagefilledrectangle($targetImg, 0, 0, 320, 65, $whiteReal);
        // 标题与二维码区域橙色背景块（与老项目布局相似）
        imagefilledrectangle($targetImg, 0, 65, 320, 350, $orange);

        // 顶部logo
        $shopLogo = public_path('static/logo.png');
        if (!file_exists($shopLogo)) {
            $shopLogo = public_path('static/images/default-logo.png');
        }

        $logoSource = $this->createImageFromUrl($shopLogo);
        $qrSource = $this->createImageFromUrl($data['qr_link']);

        $mergeData = [
            'dst_left' => 60,
            'dst_top' => 10,
            'dst_width' => 190,
            'dst_height' => 52,
        ];
        $this->mergeImage($targetImg, $logoSource, $mergeData);

        // 分隔线
        $fontColor = imagecolorallocate($targetImg, 255, 250, 250);
        imageline($targetImg, 20, 65, 300, 65, $fontColor);

        $len = mb_strlen($shopName);
        $size = 20;
        if ($len > 10) { $size = 15; }
        if ($len > 16) { $shopName = mb_substr($shopName, 0, 16); }

        // 中英文均使用 TTF 字体渲染（与老项目一致）
        $font = public_path('static/fonts/source_han_sans.ttf');
        if (!file_exists($font)) {
            // 兜底：若字体缺失，用内置字体近似定位
            $bboxWidth = strlen($shopName) * 12;
            $x = (imagesx($targetImg) - $bboxWidth) / 2;
            $black = imagecolorallocate($targetImg, 255, 250, 250);
            imagestring($targetImg, 5, (int)$x, 90, $shopName, $black);
        } else {
            $bbox = imagettfbbox($size, 0, $font, $shopName);
            $textWidth = $bbox[2] - $bbox[0];
            $textHeight = $bbox[1] - $bbox[7];
            $x = (imagesx($targetImg) - $textWidth) / 2;
            $y = 105; // 顶部店名位置
            $black = imagecolorallocate($targetImg, 255, 250, 250);
            imagettftext($targetImg, $size, 0, (int)$x, (int)$y, $black, $font, $shopName);
        }

        // 二维码白色容器（留出边框，更接近老项目样式）
        $qrBoxSize = 240;
        $canvasWidth = imagesx($targetImg);
        $qrBoxLeft = (int)round(($canvasWidth - $qrBoxSize) / 2); // 水平完全居中
        // 橙色块内，避开上方店名占位（约60px）
        $regionTop = 65 + 60;      // 店名区域高度 ~60
        $regionBottom = 350 - 10;  // 底部给一点缓冲
        $regionHeight = max(0, $regionBottom - $regionTop);
        $qrBoxTop  = (int)round($regionTop + max(0, ($regionHeight - $qrBoxSize)) / 2);
        imagefilledrectangle($targetImg, $qrBoxLeft, $qrBoxTop, $qrBoxLeft + $qrBoxSize, $qrBoxTop + $qrBoxSize, $whitePure);

        // 二维码尺寸与居中放置
        $qrSize = 250;
        $qrLeft = (int)round($qrBoxLeft + ($qrBoxSize - $qrSize) / 2); // 居中
        $qrTop  = (int)round($qrBoxTop + ($qrBoxSize - $qrSize) / 2);  // 居中
        $this->mergeImage($targetImg, $qrSource, [
            'dst_left' => $qrLeft,
            'dst_top' => $qrTop,
            'dst_width' => $qrSize,
            'dst_height' => $qrSize,
        ]);

        // 文案
        // 底部橙色条
        imagefilledrectangle($targetImg, 0, 350, 320, 440, $orange);
        // 大标题与副标题（白色文字）
        $this->mergeText($targetImg, '消 费 置 换 码', [
            'size' => 28,
            'left' => 30,
            'top' => 390,
        ]);
        $this->mergeText($targetImg, '用微信扫码置换商家商品或服务', [
            'size' => 14,
            'left' => 30,
            'top' => 418,
        ]);

        $imgPath = $path . '/' . $file;
        imagepng($targetImg, $imgPath);

        $file = $path . '/' . $file;
        $imgUrl = $this->getImageUrl($file);
        return $imgUrl;
    }

    // 合并图片并指定图片大小
    private function mergeImage($destinationImg, $sourceImg, $data)
    {
        if (!$sourceImg) {
            return $destinationImg;
        }
        
        $w = imagesx($sourceImg);
        $h = imagesy($sourceImg);
        imagecopyresized($destinationImg, $sourceImg, $data['dst_left'], $data['dst_top'], 0, 0, $data['dst_width'],
            $data['dst_height'], $w, $h);
        imagedestroy($sourceImg);
        return $destinationImg;
    }
    
    // 合并字符串（使用 TTF 字体，与老项目一致）
    private function mergeText($destinationImg, $text, $data)
    {
        $font = public_path('static/fonts/source_han_sans.ttf');
        $color = imagecolorallocate($destinationImg, 255, 250, 250);
        if (file_exists($font)) {
            imagettftext($destinationImg, $data['size'], 0, $data['left'], $data['top'], $color, $font, $text);
        } else {
            // 字体缺失兜底
            imagestring($destinationImg, 5, $data['left'], $data['top'] - 12, $text, $color);
        }
        return $destinationImg;
    }
    
    // 从URL创建图片资源
    private function createImageFromUrl($url)
    {
        if (filter_var($url, FILTER_VALIDATE_URL)) {
            // 优先将本站的 /storage 路径映射为本地文件，避免通过 HTTP 获取导致返回 HTML/权限问题
            $host = request()->getSchemeAndHttpHost();
            $path = parse_url($url, PHP_URL_PATH);
            if ($path) {
                $relative = ltrim($path, '/');
                // 公共存储目录映射
                $publicFile = public_path($relative);
                if (is_file($publicFile)) {
                    $img = $this->createImageFromLocalFile($publicFile);
                    if ($img !== false) { return $img; }
                }
                // storage 映射
                if (strpos($relative, 'storage/') === 0) {
                    $storageRel = substr($relative, strlen('storage/'));
                    $storageFile = storage_path('app/public/' . $storageRel);
                    if (is_file($storageFile)) {
                        $img = $this->createImageFromLocalFile($storageFile);
                        if ($img !== false) { return $img; }
                    }
                }
            }
            // 退回到直接通过 URL 获取
            $imageData = @file_get_contents($url);
            if ($imageData !== false) {
                $img = @imagecreatefromstring($imageData);
                if ($img !== false) { return $img; }
            }
        } elseif (is_file($url)) {
            $img = $this->createImageFromLocalFile($url);
            if ($img !== false) { return $img; }
        }
        
        // 创建默认图片
        $img = imagecreatetruecolor(200, 200);
        $bg = imagecolorallocate($img, 255, 255, 255);
        imagefill($img, 0, 0, $bg);
        $text = 'IMG N/A';
        $black = imagecolorallocate($img, 0, 0, 0);
        imagestring($img, 3, 60, 90, $text, $black);
        return $img;
    }

    private function createImageFromLocalFile(string $file)
    {
        // 优先根据扩展名选择解析方式，更稳妥
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if ($ext === 'png') {
            $img = @imagecreatefrompng($file);
            if ($img !== false) { return $img; }
        } elseif (in_array($ext, ['jpg','jpeg'])) {
            $img = @imagecreatefromjpeg($file);
            if ($img !== false) { return $img; }
        } elseif ($ext === 'gif') {
            $img = @imagecreatefromgif($file);
            if ($img !== false) { return $img; }
        }
        // 回退到通用解析
        $data = @file_get_contents($file);
        return ($data !== false) ? @imagecreatefromstring($data) : false;
    }
    
    // 获取图片URL
    private function getImageUrl($file)
    {
        $relativePath = str_replace(storage_path('app/public/'), '', $file);
        return url('storage/' . $relativePath);
    }

    private function getImgUrl($file)
    {
        return public_path('static/app/images/' . $file);
    }
}
